<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="demo">
        <input type="text" v-model="searchName">
        <ul>
            <li v-for="(person,index) in filterPersons" :key="person.id" >
                {{index}} -- {{person.name}} --{{person.age}}
            </li>
        </ul>
        <button @click="sortType=1">升序排列</button>
        <button @click="sortType=2">降序排列</button>
        <button @click="sortType=0">恢复排列</button>
    </div>
    <script src="../day02/js/vue.js"></script>
    <script>
        new Vue({
            el:'#demo',
            data:{
                searchName:'',//搜索关键字
                sortType:0,//排序的方式：0 表示不排序，1表示升序排列，2表示降序排列
                persons:[
                    {id:1,name:"wangda",age:24},
                    {id:2,name:"lier",age:19},
                    {id:3,name:"zhangsan",age:14},
                    {id:4,name:"lisi",age:38},
                    {id:5,name:"wangwu",age:27},
                    {id:6,name:"zhaoliu",age:29},
                    {id:7,name:"guoqi",age:58},
                    {id:8,name:"wnagba",age:43},
                    {id:9,name:"lixiaolu",age:23},
                ]
            },
            computed:{
                // 要显示的过滤后的数组
                filterPersons(){
                    // 取出依赖的数据
                    const {searchName,persons,sortType} = this;
                    // 计算结果
                    const arr = persons.filter(p=>{
                        return p.name.includes(searchName)
                    })
                    // 可能需要排序（排序可能是升序也可能是降序）
                    if(sortType!==0){
                        arr.sort((item1,item2)=>{
                            if(sortType === 1){
                                // 升序排列
                                return item1.age - item2.age;
                            }else{
                                // 降序排列
                                return item2.age - item1.age;
                            }
                        })
                    }
                    // 返回结果
                    return arr;
                }
            }
        })
        /* 
        练习思路：
        目的实现在输入框中输入字符，列表中的数据自动更新，用到的指令v-model
        点击升降序按钮时会发生相应的变化，以及变化后恢复原样
        */
    </script>
</body>
</html>